<?php
/**
 * ==============================================
 * Copy right 2015-2016 http://wei.meididi88.com
 * ----------------------------------------------
 * This is not a free software, without any authorization is not allowed to use and spread.
 * ==============================================
 * @author: hy
 * @date: 2015-9-10
 * @version: v1.0.0
 */
namespace Common\Model;

use Think\Model;

/**
 * 服务项目使用产品 Model模型类
 */
class ServiceUseProductModel extends Model{
	
	/**
	 * 生成查询条件
	 * 
	 * @param array $where
	 * @return array
	 */
	public function createWhere($where) {
		return $where;
	}
	
	/**
	 * 清除实例对象图片缓存
	 *
	 * @param number $target_id	服务项目编号
	 */
	public function clearCache($target_id) {
		$key = $this->getCacheKey($target_id);
		S($key, null);
	}
	
	/**
	 * 编辑服务使用产品
	 *
	 * @param number $target_id	服务项目编号
	 * @param array $products	服务项目使用产品
	 * @return boolean
	 */
	public function editUseProduct($target_id, $submit_products) {
		$useProducts = $this->getTargetUseProduct($target_id);
		$products = array();
		if ($useProducts) {
			$products = array_map(function ($var) {
				return $var ['product_id'];
			}, $useProducts);
		}
	
		if (!$submit_products) {
			$submit_products = array();
		}
		
		$deleteProductUse = array_diff($products, $submit_products);
		$addProductUse = array_diff($submit_products, $products);
		
		if ($deleteProductUse) {
			foreach ($deleteProductUse as $dKey => $dValue) {
				$where = array('id' => $useProducts [$dKey] ['id']);
				$deleteResult = $this->where($where)->save(array('status' => 0));
				if (!$deleteResult) {
					return false;
				}
			}
			//触发文件清除方法
		}
		
		if ($addProductUse) {
			foreach ($addProductUse as $aKey => $aValue) {
				$productData = array(
					'target_id' => $target_id,
					'product_id' => $aValue,
				);
				$result = $this->where($productData)->find();
				if ($result) {
					$updateResult = $this->where(array('id' => $result ['id']))->save(array('status' => 1));
					if (!$updateResult) {
						return false;
					}
				} else {
					$productData ['created'] = time();
					
					$addResult = $this->add($productData);
					if (!$addResult) {
						return false;
					}
				}
			}
		}
	
		$this->clearCache($target_id);
		return true;
	}
	
	/**
	 * 生成缓存key
	 * 
	 * @param number $target_id	服务项目编号
	 * @return string
	 */
	public function getCacheKey($target_id) {
		return 'Product_'.$target_id;
	}
	
	/**
	 * 获取实例所使用产品
	 * 
	 * @param number $target_id	服务项目编号
	 * @return boolean|array
	 */
	public function getTargetUseProduct($target_id) {
		$key = $this->getCacheKey($target_id);
		
		$photos = S($key);
		if (!$photos) {
			$where = $this->createWhere(array(
				'target_id'	=> $target_id,
				'status'	=> 1
			));
			$photos = $this->where($where)->select();
			S($key, $photos);
		}
		
		return $photos;
	}
	
}